//
//  AppDelegate.swift
//  sinaWeiBoGui
//
//  Created by liyonggui on 16/5/9.
//  Copyright © 2016年 liyonggui. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 设置导航行的皮肤
        setupAppearance()
//        YGPrint(items: "\(application)")
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        // 主控制器
        let tabBarVC = YGMainTabBarViewController()
        tabBarVC.view.backgroundColor = UIColor.whiteColor()
        
        // 测试welcomViewController
//        let welocmVC = YGWelcomViewController()
        
        // 测试newFeatureViewController
//        let newVC = YGNewFeatureViewController()
        
        // 根控制器
        window?.rootViewController = defaultViewController()
        
        window?.makeKeyAndVisible()
        
        // 测试账号保存
        let account = YGUserAccountViewModel.sharedInstance.userAccount
        YGPrint(items: "account : \(account)")
        
        // 测试登录情况
//        let isLogin = YGUserAccountViewModel.sharedInstance.isUserLogin
//        print("isLogin: \(isLogin)")
        
        // 测试是否版本
//        let isNewVersiona = isNewVersion()
//        print("isLogin: \(isNewVersiona)")
        
        return true
    }
    
    /// 显示默认的控制器
    private func defaultViewController() -> UIViewController {
        // 没登录
        if !YGUserAccountViewModel.sharedInstance.isUserLogin {
            return YGMainTabBarViewController()
        }
        
        // 已登录，检查是否新版本
        if isNewVersion() {
            return YGNewFeatureViewController()
        } else {
            return YGWelcomViewController()
        }
    }
    
    /// 切换window的根控制器
    func switchController(controller: UIViewController) {
        window?.rootViewController = controller
    }
    
    /// 判断是否新版本
    private func isNewVersion() -> Bool {
        // 获取当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        // 获取上次版本
        let lastVersionKey = "lastVersionKey"
        let lastVersion = NSUserDefaults.standardUserDefaults().stringForKey(lastVersionKey)
        
        // 比较
        let isNewVersion = currentVersion != lastVersion
        
        // 如果是新版,更新保存的版本
        if isNewVersion {
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: lastVersionKey)
            // 同步
            NSUserDefaults.standardUserDefaults().synchronize()
        }
        
        return isNewVersion
    }
    
    
    
    /// 设置导航行的皮肤
    private func setupAppearance() {
        let bar = UINavigationBar.appearance()
        bar.tintColor = UIColor.orangeColor()
    }
}

